package com.wang.users.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.common.pojo.BasePojoEnum;
import com.wang.common.util.BeanUtil;
import com.wang.common.util.ConstatFinalUtil;
import com.wang.users.mapper.AtUsersOrganMapper;
import com.wang.users.pojo.AtUsersOrgan;
import com.wang.users.pojo.AtUsersOrganEnum;
import com.wang.users.pojo.AtUsersOrganQuery;
import com.wang.users.service.AtUsersOrganService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 针对表【at_demo_dynasty(示例_朝代表)】的数据库操作Service实现
 *
 * @author ZjxMi
 */
@Service
public class AtUsersOrganServiceImpl extends ServiceImpl<AtUsersOrganMapper, AtUsersOrgan>
        implements AtUsersOrganService {

    @Autowired
    private BeanUtil beanUtil;

    @Override
    public AtUsersOrgan findTreeList(String id) {
        /* 根据id查询数据 */
        AtUsersOrganQuery paramQuery = new AtUsersOrganQuery();
        AtUsersOrgan entityCond = paramQuery.getEntity();
        entityCond.setId(id);
        AtUsersOrgan dbResult = this.findOne(paramQuery);
        if (Objects.nonNull(dbResult)) {
            /* 查询节点 */
            List<AtUsersOrgan> resultList = new ArrayList<>();
            this.findTreeListUtil(dbResult, resultList);
            Collections.reverse(resultList);

            /* 存储结果 */
            dbResult.setParentList(resultList);
            StringBuilder sb = new StringBuilder();
            for (AtUsersOrgan dataTemp : resultList) {
                sb.append(dataTemp.getName()).append(ConstatFinalUtil.BLANK_STRING_FINAL);
            }
            dbResult.setTreeName(sb.toString());
        }
        return dbResult;
    }

    public void findTreeListUtil(AtUsersOrgan dataTemp, List<AtUsersOrgan> resultList) {
        if (Objects.nonNull(dataTemp)) {
            resultList.add(dataTemp);
            /* 根据id查询数据 */
            AtUsersOrganQuery paramQuery = new AtUsersOrganQuery();
            AtUsersOrgan entityCond = paramQuery.getEntity();
            entityCond.setId(dataTemp.getParentId());
            AtUsersOrgan dbResult = this.findOne(paramQuery);
            findTreeListUtil(dbResult, resultList);
        }
    }


    /**
     * model2: jsp --> servlet -->service --> dao --> db, 我们自己封装了一个 PageInfoUtil;
     * MybatisPlus: 不再需要调用 PageInfoUtil,老代码改造的时候是为了整合代码,如果没有老代码,直接写的新代码,采用下面的方式来搞
     *
     * @param page
     * @param query 查询对象
     * @return
     */
    @Override
    public List<AtUsersOrgan> findList(IPage<AtUsersOrgan> page, AtUsersOrganQuery query) {
        if (page != null) {
            return this.baseMapper.findList(page, query);
        }
        return this.baseMapper.findList(query);
    }

    @Override
    public AtUsersOrgan findOne(AtUsersOrganQuery query) {
        return this.baseMapper.findOne(query);
    }

    @Override
    public int updateBatch(AtUsersOrganQuery query) {
        return this.baseMapper.updateBatch(query);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteBatch(AtUsersOrganQuery query) {
        /* 根据id查询对象 */
        AtUsersOrgan currObj = this.findOne(query);
        if (Objects.nonNull(currObj)) {
            /* 查询父节点 */
            AtUsersOrganQuery paramQuery = new AtUsersOrganQuery();
            AtUsersOrgan entityCond = paramQuery.getEntity();
            entityCond.setId(currObj.getParentId());
            AtUsersOrgan parentObj = this.findOne(paramQuery);
            if (parentObj != null) {
                paramQuery = new AtUsersOrganQuery();
                entityCond = paramQuery.getEntity();
                entityCond.setParentId(parentObj.getId());
                IPage<AtUsersOrgan> paramPage = new Page<>(paramQuery.getCurrent(), paramQuery.getSize());
                List<AtUsersOrgan> dataList = this.findList(paramPage, paramQuery);
                if (paramPage.getTotal() == 1) {
                    parentObj.setIsLeafStatus(AtUsersOrganEnum.LEAFSTATUS_YES.getCode());
                    this.updateById(parentObj);
                }
            }
        }
        return this.baseMapper.deleteBatch(query);
    }

    /**
     * 对数据额外处理(非用户填写的数据)
     *
     * @param entity
     */
    private void proccedUpdateData(AtUsersOrgan entity) {
        if (Objects.isNull(entity.getCreateTime())) {
            entity.setCreateTime(new Date());
        }
        entity.setUpdateTime(new Date());
        /* 判断对象是否为空 */
        if (Objects.isNull(entity.getPubTime())) {
            entity.setPubTime(new Date());
        }
        /* 为rootId赋值 */
        if (StringUtils.isEmpty(entity.getParentId())) {
            entity.setParentId(AtUsersOrganQuery.ROOT_ID_FINA);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean save(AtUsersOrgan entity) {
        this.proccedUpdateData(entity);
        entity.setIsLeafStatus(AtUsersOrganEnum.LEAFSTATUS_YES.getCode());
        /* 新增加的记录默认未删除 */
        entity.setDelFlag(BasePojoEnum.DELFLAG_NO.getCode());
        boolean dbFlag = super.save(entity);
        if (dbFlag) {
            if (StringUtils.isNotEmpty(entity.getParentId())) {
                /* 更新父节点 */
                AtUsersOrganQuery paramQuery = new AtUsersOrganQuery();
                AtUsersOrgan entityCond = paramQuery.getEntity();
                entityCond.setId(entity.getParentId());
                AtUsersOrgan parentObj = this.findOne(paramQuery);
                if (parentObj != null) {
                    parentObj.setIsLeafStatus(AtUsersOrganEnum.LEAFSTATUS_NO.getCode());
                    this.updateById(parentObj);
                }
            }
        }
        return dbFlag;
    }

    @Override
    public boolean updateById(AtUsersOrgan entity) {
        /* 先根据id查询数据库的内容; */
        AtUsersOrganQuery paramQuery = new AtUsersOrganQuery();
        AtUsersOrgan entityParam = paramQuery.getEntity();
        entityParam.setId(entity.getId());
        /* 数据库中查询的结果 */
        AtUsersOrgan oneDbResult = this.findOne(paramQuery);
        oneDbResult.setParentObj(null);
        /*
         * 源对象和目标对象是一个类型(10个字段)
         * 源对象有5个字段有值,目标对象是10个有值
         * 把源对象中的5个字段有值,赋值到目标对象中.(覆盖)
         * */
        oneDbResult = (AtUsersOrgan) this.beanUtil.copy(entity, oneDbResult);

        this.proccedUpdateData(oneDbResult);
        return super.updateById(oneDbResult);
    }
}